import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import koaStatic from 'koa-static'
import logger from 'koa-logger'
import router from './router/index.js'
import path, { dirname } from 'node:path'
import { fileURLToPath } from 'url'
import { errorHandler } from './middleware/index.js'

// Capture unprocessed exceptions
process.on('uncaughtException', (err, origin) => {
  console.log(`Caught exception: ${err}\n` + `Exception origin: ${origin}`)
})

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const app = new Koa()
app.use(logger())
app.use(koaStatic(path.join(__dirname, '..', 'client/dist')))
// Process POST requests, parse the data in the request body, and place it on the ctx.request.body object
app.use(bodyParser())

// Unified interface error handling
app.use(errorHandler)

// Register routing middleware
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000, () => {
  console.log('The server is running on http://127.0.0.1:3000')
})
